<?php

/**
 * 管理员管理
 *
 * @author suning <snsnsky@gmail.com>
 */

use \Common\Bridge;
use \Passport\Account;

define("SITE_AUTH", 'admin-user');
require '../../../common.inc.php';

class User extends lib\core\AdminAction
{
    public function doDefault()
    {
        $group = \Admin\AdminAuth::getAllGroup();
        $groupselect = '';
        foreach ($group as $v)
        {
            $groupselect .= "<option value='{$v['AdminGroupId']}'>{$v['GroupName']}</option>";
        }

        $db = Bridge::pdo(Bridge::DB_ADMIN_R);
        $count = $db->query("select count(*) as num from AdminUser")->fetch();
        $count = $count['num'];

        $now = intval($_GET['page']) > 0 ? intval($_GET['page']) : 1;
        $per = self::PAGE_SIZE;//每页20
        $offset = ($now-1)*$per;

        $pagination = $this->pagination($count, $per, $now);
        $user = \Admin\AdminAuth::getAdminUser($offset, $per);

        $page = $this->app->page();
        $page->value("groupselect", $groupselect);
        $page->value("user", $user);
        $page->value("pagination", $pagination);
        $page->output('admin/user.tpl');
    }

    public function doEdit()
    {
        $uid = intval($_GET['userid']);

        if (isset($_POST['user_name']))
        {
            //保存
            $dbw = Bridge::pdo(Bridge::DB_ADMIN_W);

            $auth = serialize($_POST['menu']);
            $name = strval($_POST['user_name']);
            $group = intval($_POST['auth_group']);

            $re = $dbw->update('AdminUser', ['AdminUserGroup'=>$group,'AdminUserName'=>$name,'SpecialGroups'=>$auth], ['AdminUserId'=>$uid]);
            if ($re !== false)
            {
                $this->adminLog('编辑管理员', $uid, 'update', serialize($_POST));
                HDshowMsg('保存成功',['url'=>ADMIN_MODULES.'admin/user.php']);
            }
            HDshowMsg('保存失败',['type'=>'error']);
        }

        $menu = \Admin\Menu::getAllMenu();

        $user = \Admin\AdminAuth::getAdminUserById($uid);
        $auth = unserialize($user['SpecialGroups']);
        $auth = array_combine((array)$auth, (array)$auth);

        $group_auth = unserialize($user['GroupData']['AdminAuth']);
        $group_auth = array_combine((array)$group_auth, (array)$group_auth);

        $group = \Admin\AdminAuth::getAllGroup();
        $groupselect = '';
        foreach ($group as $v)
        {
            if ($user['AdminUserGroup'] == $v['AdminGroupId'])
            {
                $groupselect .= "<option value='{$v['AdminGroupId']}' selected='selected'>{$v['GroupName']}</option>";
            }
            else
            {
                $groupselect .= "<option value='{$v['AdminGroupId']}'>{$v['GroupName']}</option>";
            }
        }

        $page = $this->app->page();
        $page->value("user", $user);
        $page->value("menu", $menu);
        $page->value("auth", $auth);
        $page->value("group_auth", $group_auth);
        $page->value("groupselect", $groupselect);
        $page->output('admin/user_edit.tpl');
    }

    public function doSearchUser()
    {
        $key = $_GET['key'];
        $length = strlen($key);

        if(is_numeric($key) && $length == 11)
        {
            $user = Account::getUserById(Account::getUserIdByMobile($key));
        }
        elseif (is_numeric($key))
        {
            $user = Account::getUserById($key);
        }
        else
        {
            $user = Account::getUserById(Account::getUserIdByEmail($key));
        }

        if (empty($user))
        {
            $this->output([]);
        }
        $this->output($user);
    }

    public function doAddAdmin()
    {
        $uid = intval($_POST['userid']);
        $name = strval($_POST['true_name']);
        $groupid = intval($_POST['groupid']);

        $user = Account::getUserById($uid);
        if (empty($user))
        {
            $this->output(['title'=>'用户不存在','type'=>'error']);
        }
        $exi = \Admin\AdminAuth::getAdminUserById($uid);
        if (!empty($exi))
        {
            $this->output(['title'=>'此用户已经是管理员','type'=>'error']);
        }

        $data['AdminUserId'] = $uid;
        $data['AdminUserGroup'] = $groupid;
        $data['AdminUserName'] = $name;

        $db = Bridge::pdo(Bridge::DB_ADMIN_W);

        $re = $db->insert('AdminUser', $data);
        if ($re > 0)
        {
            $this->adminLog('添加管理员', $db->lastInsertId(), 'add', serialize($data));
            $this->output(['title'=>'添加成功','type'=>'success']);
        }
        $this->output(['title'=>'添加失败','type'=>'error']);
    }

    /**
     * 删除管理员
     */
    public function doDel()
    {
        $uid = intval($_GET['userid']);

        $dbw = Bridge::pdo(Bridge::DB_ADMIN_W);

        $re = $dbw->delete('AdminUser', ['AdminUserId'=>$uid]);
        if ($re > 0)
        {
            $this->adminLog('删除管理员', $uid, 'del', $uid);
            HDshowMsg('删除成功');
        }
        HDshowMsg('删除失败，请重试',['type'=>'error']);
    }
}

$app->run();